﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Collections;
using System.Globalization;
using DevExpress.XtraGrid.Views.Grid.ViewInfo;
using System.IO;
using DevExpress.Utils;

namespace BSC_OTC_Management.Forms.SoTraiChu
{
    public partial class Frm_ThanhToanLaiGoc : Form
    {

        #region Khai bao bien
        string _formName = "BSC_TBL_TLLOGTTLAI";
        DataTable _tableData = new DataTable();
        DataTable _tableSoTraiChu = new DataTable();
        DataTable _tableView = new DataTable();
        DataTable _logTA = new DataTable();//table luu giu cac thong tin duyet giao dich

        DataTable _tableSTCTTLai = new DataTable("TLLOGTTLAI");
        DataTable _tableViewTLLOGTTLAI = new DataTable("ViewTLLOGTTLAI");
        Code.CL_Ultility _cl = new Code.CL_Ultility();
        string _matp = "";
        string _macoupon = "";
        string _dotgopvon = "";
        #endregion

        public Frm_ThanhToanLaiGoc()
        {
            InitializeComponent();
            this.splitContainer1.Panel2.Enabled = false;
        }

        #region Event

        private void Frm_ThanhToanLaiGoc_Load(object sender, EventArgs e)
        {
            LoadData();
            LoadDataGrid(_tableData,_tableView, gridControl1, gridView1);
            this.AcceptButton = btn_Search;
            //LoadTPPH();
        }

        private void btn_Search_Click(object sender, EventArgs e)
        {
            string ngayttlai = DateTime.ParseExact(dt_ngayttlai.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture).ToString("dd/MM/yyyy");
            //string tentp = ((KeyValuePair<string,string>)cbbMaTPPH.SelectedItem).Key;
            string tentp = txtTraiphieuphathanh.Text;
            string condition = "";

            condition = " and a.ngayttlai <= TO_DATE('" + ngayttlai + "','dd/MM/yyyy')" +
                        " and Upper(b.tentp) like '%" + tentp.ToUpper() + "%'" +
                        " and a.trangthai = 0 and a.duyet = 1";

            DataTable _dt = new DataTable("coupon_searching");
            _dt = _cl._services.SearchView_BySQL("BSC_TBL_COUPON", condition);

            LoadDataGrid(_dt,_tableView,gridControl1,gridView1);
        }

        private void Frm_ThanhToanLaiGoc_FormClosed(object sender, FormClosedEventArgs e)
        {
            this.Close();
        }    

        private void btnTinhLai_Click(object sender, EventArgs e)
        {
            try
            {
                string sql = "select * from bsc_tbl_coupon where macoupon ='" + value + "'";
                _logTA = _cl._services.GetDatatable_BySQL(sql);
                if (_logTA.Rows.Count > 0)
                {
                    _macoupon = _logTA.Rows[0]["macoupon"].ToString();
                    _matp = _logTA.Rows[0]["matp"].ToString();
                    _dotgopvon = _logTA.Rows[0]["dotgopvon"].ToString();
                    _tableSoTraiChu = _cl._services.Get_List_Sotraichu_BY_NgayTTlai(_matp, _macoupon, _dotgopvon);
                }

                DataTable noname = new DataTable("noname");
                foreach (DataColumn col in _tableSoTraiChu.Columns)
                {
                    noname.Columns.Add(col.ColumnName, typeof(String));
                }

                if (_tableSoTraiChu.Rows.Count > 0)
                {
                    for (int i = 0; i < _tableSoTraiChu.Rows.Count; i++)
                    {

                        noname.Clear();

                        //create new row
                        DataRow rowValue = noname.NewRow();
                        DataRow rowType = noname.NewRow();

                        //add value to row
                        for (int j = 0; j < noname.Columns.Count; j++)
                        {
                            rowValue[j] = _tableSoTraiChu.Rows[i][j];
                            if (_tableSoTraiChu.Columns[j].DataType == typeof(DateTime))
                                rowType[j] = "D";
                            else
                                rowType[j] = "T";

                        }
                        noname.Rows.Add(rowValue);
                        noname.Rows.Add(rowType);
                        //noname.Rows.Add(_tableSoTraiChu.Rows[i].ItemArray);
                        string store = "bsc_201.Thanh_toan_lai_goc";
                        string _result = _cl._services.Excute_Store_Transaction(store, noname);
                        if (_result != "0")
                            throw new Exception(_result);
                    }
                    //Update_Coupon_Status
                    if (!_cl._services.Update_Coupon_Status(_macoupon, 2))//2:đang thanh toán coupon và chờ duyệt
                        throw new Exception(Code.StaticVariable.messeseboxThatBai);
                    else
                        MessageBox.Show(Code.StaticVariable.messeseboxThanhCong, Code.StaticVariable.messeseboxLuuY);

                    //luu vet nguoi thuc hien
                    _cl._services.Update_Last_Change_By_ColumnName(_formName, "MACOUPON", _macoupon, Code.StaticVariable.userID);
                                
                    //tinh lai ok chuyen sang duyet
                    this.splitContainer1.Panel2.Enabled = true;
                    this.splitContainer1.Panel1.Enabled = false;
                    //

                    //load thong tin so dang thanh toan
                    Load_Sotraichu_TTLai(value.ToString());
                    //thay ten cot
                    LoadDataGrid(_tableSTCTTLai, _tableViewTLLOGTTLAI, this.gridControl2, this.gridView2);
                }
                else
                    MessageBox.Show("Không có Trái phiếu nào đến hạn thanh toán lãi/gốc.", Code.StaticVariable.messeseboxLuuY);
            }
            catch(Exception ex){
                MessageBox.Show(ex.Message,Code.StaticVariable.messeseboxLuuY);
            }
        }

        //khai báo đối tượng cho row
        object value = null;
        void gridView1_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == System.Windows.Forms.MouseButtons.Left)
            {
                GridHitInfo hi = gridView1.CalcHitInfo(e.Location);

                if (hi.InRowCell)
                {
                    value = gridView1.GetRowCellValue(hi.RowHandle, "MACOUPON");
                    if (value != null)
                    {
                        stt_Lable.Text = "Bạn đang chọn coupon " + value.ToString() + ".";
                        stt_Lable.ForeColor = Color.Red;
                        stt_Status.Refresh();
                    }
                }
            }
        }

        #endregion

        #region ham

        //_dt bang nguon, _tableView bang du lieu ten cot
        private void LoadDataGrid(DataTable _dt, DataTable _tableView, DevExpress.XtraGrid.GridControl gridControl, DevExpress.XtraGrid.Views.Grid.GridView gridView)
        {
            try
            {
                bool duyet = false;
                DataTable view = new DataTable("View");
                foreach (DataColumn col in _dt.Columns)
                {
                    if (col.ColumnName == "DUYET")
                    {
                        duyet = true;
                        view.Columns.Add(col.ColumnName, typeof(String));
                    }
                    else
                        view.Columns.Add(col.ColumnName, col.DataType);
                }

                for (int i = 0; i < _dt.Rows.Count; i++)
                {
                    view.Rows.Add(_dt.Rows[i].ItemArray);
                }

                //add duyet
                if (duyet)
                {
                    DataTable tblduyet = new DataTable("Duyet");
                    tblduyet = _cl._services.GetDatatable_BySQL("select * from allcode where cdtype = 'AP' and cdname = 'DUYET' and cduser='Y' ORDER BY lstodr");
                    for (int i = 0; i < view.Rows.Count; i++)
                    {
                        for (int j = 0; j < tblduyet.Rows.Count; j++)
                        {
                            if (view.Rows[i]["DUYET"].ToString() == tblduyet.Rows[j]["CDVAL"].ToString())
                                view.Rows[i]["DUYET"] = tblduyet.Rows[j]["CDCONTENT"];
                        }
                    }
                }

                // Thay tên dựa theo FieldCode, FieldName
                gridControl.DataSource = view;

                foreach (DevExpress.XtraGrid.Columns.GridColumn column in gridView.Columns)
                {

                    //thay ten column
                    foreach (DataRow row in _tableView.Rows)
                    {
                        if (row["fldname"].ToString().ToUpper() == column.ToString())
                        {
                            gridView.Columns[column.ToString()].Caption = row["caption"].ToString(); ;
                        }
                    }

                    //dinh dang truong so cho cell
                    if (column.ColumnType == typeof(System.Decimal))
                    {
                        column.DisplayFormat.FormatType = FormatType.Numeric;
                        column.DisplayFormat.FormatString = "#,##0.###";
                    }
                }

                gridView.BestFitColumns();
                //datnt: dont edit any cell in gridView
                gridView.OptionsBehavior.Editable = false;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, Code.StaticVariable.messeseboxLuuY);
            }
        }

        private void LoadData()
        {
            // Load du lieu vao table
            //this._tableData = _cl._services.Get_Table_TTTraLaiTP();
            /*this._tableData = _cl._services.SearchView_BySQL("BSC_TBL_COUPON", "");*/
            this._tableView = _cl._services.GetViewBy_SearchCode("BSC_TBL_COUPON");
            this._tableViewTLLOGTTLAI = _cl._services.GetViewBy_SearchCode("BSC_TBL_TLLOGTTLAI");
        }

        private void Load_Sotraichu_TTLai(string _macoupon)
        {
            try
            {
                //command text
                string sql = "Select tl.macoupon, tl.matp, tl.makh, tl.maso, tl.matk, ac.cdcontent thanhtoangoc, st.slphothong, st.slhanche, st.slcamco,tl.tienlai,tl.tlphongtoa,tl.tiengoc,tl.tgphongtoa,tl.tong,al.cdcontent trangthaicoupon "
                            + "from bsc_tbl_tllogttlai tl, bsc_tbl_sotraichu st, allcode al, allcode ac "
                            + "where tl.trangthaicoupon = al.cdval and tl.thanhtoangoc = ac.cdval "
                            + "and  tl.maso = st.maso "
                            + "and al.cdname = 'TRANGTHAI' and al.cdtype = 'BSC_TBL_COUPON' "
                            + "and ac.cdname = 'THANHTOANGOC' and ac.cdtype = 'BSC_TBL_COUPON' "
                            + "and tl.trangthaicoupon = 2 "
                            + "and tl.macoupon ='" + _macoupon + "'";
                _tableSTCTTLai = _cl._services.GetDatatable_BySQL(sql);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

        }
        #endregion

        private void btn_Exit_Click(object sender, EventArgs e)
        {
            //từ chối thanh toán lãi/gốc này
            //delete all rows which have macoupon = this value in bsc_tbl_tllogttlai?
            if (!_cl._services.Excute_DB("delete bsc_tbl_tllogttlai where macoupon = " + value.ToString()))
            {
                MessageBox.Show(Code.StaticVariable.messeseboxThatBai, Code.StaticVariable.messeseboxLuuY);
                return;
            }

            //update status of coupon in bsc_tbl_coupon 2 -> 0
            if (_cl._services.Update_Coupon_Status(value.ToString(), 0))//0: chua thanh toan
            {
                this.gridControl2.DataSource = null;
                this.gridControl2.Refresh();
                MessageBox.Show(Code.StaticVariable.messeseboxHuyDuyetThanhCong, Code.StaticVariable.messeseboxLuuY);
            }
            else
                MessageBox.Show(Code.StaticVariable.messeseboxThatBai, Code.StaticVariable.messeseboxLuuY);
            //
            this.Close();
        }

        private void bt_Confirm_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void bt_Export_Click(object sender, EventArgs e)
        {
            if (this.gridView2.RowCount > 0)
            {
                using (SaveFileDialog saveDialog = new SaveFileDialog())
                {
                    saveDialog.Filter = "Excel (2003)(.xls)|*.xls|Excel (2010) (.xlsx)|*.xlsx |Pdf File (.pdf)|*.pdf |Html File (.html)|*.html";
                    if (saveDialog.ShowDialog() != DialogResult.Cancel)
                    {
                        string exportFilePath = saveDialog.FileName;
                        string fileExtenstion = new FileInfo(exportFilePath).Extension;

                        switch (fileExtenstion)
                        {
                            case ".xls":
                                gridControl2.ExportToXls(exportFilePath);
                                break;
                            case ".xlsx":
                                gridControl2.ExportToXlsx(exportFilePath);
                                break;
                            case ".pdf":
                                gridControl2.ExportToPdf(exportFilePath);
                                break;
                            case ".html":
                                gridControl2.ExportToHtml(exportFilePath);
                                break;
                            default:
                                break;
                        }

                        if (File.Exists(exportFilePath))
                        {
                            try
                            {
                                //Try to open the file and let windows decide how to open it.
                                System.Diagnostics.Process.Start(exportFilePath);
                            }
                            catch
                            {
                                String msg = "File không thể mở." + Environment.NewLine + Environment.NewLine + "Path: " + exportFilePath;
                                MessageBox.Show(msg, Code.StaticVariable.messeseboxLuuY);
                            }
                        }
                        else
                        {
                            String msg = "File không thể lưu trữ." + Environment.NewLine + Environment.NewLine + "Path: " + exportFilePath;
                            MessageBox.Show(msg, Code.StaticVariable.messeseboxLuuY);
                        }
                    }
                }
            }
        } 
    }
}
